package org.example.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.Entity.Category;
import org.example.common.R;
import org.example.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加菜品分类或者套餐分类
     * @param category
     * @return
     */
    @PostMapping("")
    public R<String> add(@RequestBody Category category){
        log.info("添加分类，分类信息：{}",category.toString());
        categoryService.save(category);
        return R.success("添加成功！");
    }

    /**
     * 分页查询所有分类
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){
        log.info("page = {},pageSize = {}",page,pageSize);
        //mybatis plus 分页先查询总记录数，再查询分页数据
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 删除某个分类
     * @param ids 分类id
     * @return
     */
    @DeleteMapping("")
    public R<String> delete(Long ids){
        log.info("删除分类，id为：{}",ids);

        categoryService.remove(ids);
        return R.success("删除成功！");
    }


    /**
     * 修改某个分类
     * @param category
     * @return
     */
    @PutMapping("")
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息：{}",category);
        categoryService.updateById(category);
        return R.success("修改成功！");
    }


    /**
     * 查询某个分类类别下的所有分类
     * @param category
     * @return
     */
    @GetMapping("list")
    public R<List<Category>> list(Category category){
        log.info("查询分类，条件为：{}",category);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null,Category::getType,category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        return R.success(categoryService.list(queryWrapper));
    }
}
